package com.settlement.system.controller;

import com.settlement.system.common.enums.ReturnStatusEnum;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.model.entity.common.BaseModel;
import com.settlement.system.model.entity.common.BasePager;
import com.settlement.system.model.entity.common.SinglePage;
import com.settlement.system.model.entity.common.SystemUser;
import com.settlement.system.reply.ObjectDataResponse;
import com.alibaba.fastjson2.JSON;
import com.settlement.system.common.util.common.BeanValidator;
import com.settlement.system.common.util.common.RedisUtil;
import com.settlement.system.common.util.common.SystemUserUtil;
import com.settlement.system.service.IBaseService;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 基础控制器
 * @author
 * @param <ModelType>
 */
@Slf4j
public abstract class BaseController<ModelType extends BaseModel> {

    protected IBaseService baseService;

    /**
     * init
     * @return
     */
    public abstract IBaseService init();

    @PostConstruct
    public void initConfig() {
        baseService = init();
    }

    public void processModel(BasePager<Map<String, Object>> model) {

    }

    /**
     * 设置默认值
     *
     * @param model
     */
    public void setDefualt(ModelType model) {
        SystemUserUtil.setDefualt(model);
    }


    /**
     * 构造请求参数
     *
     * @param request
     * @return
     */
    protected Map<String, Object> buildParam(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>(16);
        for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
            String value = entry.getValue()[0];
            if (!StringUtils.isEmpty(value)) {
                params.put(entry.getKey(), value);
            }
        }
        return params;
    }

    @ApiOperation("插入操作")
    @RequestMapping(value = "save", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse insert(@RequestBody ModelType model, HttpServletRequest request) throws ServiceException {
        try {
            setDefualt(model);
            setModelValue(model);
            baseService.insert(model);
            return new ObjectDataResponse(200, "新增成功");
        } catch (Exception ex) {
            throw new ServiceException("新增失败，请联系管理员！",ex);
        }
    }

    @ApiOperation("删除操作")
    @RequestMapping(value = "delete", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse delete(@RequestBody ModelType model, HttpServletRequest request) throws ServiceException {
        try {
            baseService.deleteById(model);
            return new ObjectDataResponse(200, "删除成功");
        } catch (Exception ex) {
            throw new ServiceException("删除失败，请联系管理员！",ex);
        }
    }

    @ApiOperation("更新操作")
    @RequestMapping(value = "update", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse update(@RequestBody ModelType model, HttpServletRequest request) throws ServiceException {
        try {
            setDefualt(model);
            setModelValue(model);
            baseService.update(model);
            return new ObjectDataResponse(200, "更新成功");
        } catch (Exception ex) {
            throw new ServiceException("更新失败，请联系管理员！",ex);
        }
    }


    @ApiOperation("批量删除操作")
    @RequestMapping(value = "batchDelete", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse batchDelete(@RequestBody List<ModelType> deleteList, HttpServletRequest request) throws ServiceException {
        try {
            for (ModelType info : deleteList) {
                if (StringUtils.isEmpty(info.getId())) {
                    throw new ServiceException("Id 不能为空");
                }
            }
            baseService.batchDelete(deleteList);
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_SUCCESS);
        } catch (Exception ex) {
            throw new ServiceException("批量删除数据失败，请联系管理员！",ex);
        }
    }

    @ApiOperation("分页查询")
    @RequestMapping(value = "list", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse getPageList(HttpServletRequest request, @RequestBody BasePager<Map<String, Object>> model) throws ServiceException {
        Map<String, Object> result = new HashMap<>(16);
        try {
            insetMenuMemory(model.getModel());
            processModel(model);
            setParamsModel(model.getModel());
            int count = baseService.selectCount(model.getModel());
            List<ModelType> rows = baseService.selectByPage(new SinglePage(model), model.getModel(),
                    model.getOrderByField(), model.getOrderBy());
            result.put("rows", rows);
            result.put("total", count);
            setFootModel(result, model.getModel());
        } catch (Exception ex) {
            throw new ServiceException("获取列表出错",ex);
        }
        return new ObjectDataResponse<Map>(result, 200, "获取列表成功");
    }

    protected ObjectDataResponse getPageList2(HttpServletRequest request, @RequestBody BasePager<Map<String, Object>> model) throws ServiceException {
        Map<String, Object> result = new HashMap<>(16);
        try {
            insetMenuMemory(model.getModel());
            processModel(model);
            setParamsModel(model.getModel());
            List<BaseModel> rows = init().selectByPage(new SinglePage(model), model.getModel(),
                    model.getOrderByField(), model.getOrderBy());
            result.put("rows", rows);
            setFootModel(result, model.getModel());
        } catch (Exception ex) {
            throw new ServiceException("获取列表出错",ex);
        }
        return new ObjectDataResponse<Map>(result, 200, "获取列表成功");
    }


    protected void insetMenuMemory(Map<String, Object> model) {
        SystemUser systemUser = SystemUserUtil.getSystemUser();
        final String menuNoKey = "menuNo";
        if (model != null && model.get(menuNoKey) != null) {
            String menuNo = (String) model.get(menuNoKey);
            //String menuName = "WP-商户配置";
            if (systemUser != null && !StringUtils.isEmpty(systemUser.getLoginName()) && !StringUtils.isEmpty(menuNo)) {
                RedisUtil.hset(systemUser.getLoginName(), menuNo, JSON.toJSONString(model));
            }
        }
    }


    /**
     * 查询合计值
     *
     * @param result
     * @param model
     */
    protected void setFootModel(Map<String, Object> result, Map<String, Object> model) throws ServiceException {
    }


    /**
     * 更改参数变量
     *
     * @param model
     */
    protected void setParamsModel(Map<String, Object> model) {
    }

    /**
     * 其他参数拼接
     *
     * @param model
     * @throws Exception
     */
    protected void setModelValue(ModelType model) throws Exception {

    }

    public static <T> T clearBeanStringBlank(T t) {
        return BeanValidator.clearBeanStringBlank(t);
    }

    public static<T> void clearBeanStringBlank(List<T> list){
        BeanValidator.clearBeanStringBlank(list);
    }
}
